#!/usr/bin/env python3

import requests
import time
import random

# 需手动修改这里：按照 "文章链接->访问次数" 的格式添加要访问的文章
URL_VISITS = [
    "https://blog.csdn.net/2301_80863610/article/details/146934154?spm=1001.2014.3001.5501->150",
    "https://blog.csdn.net/2301_80863610/article/details/146970940?spm=1001.2014.3001.5501->150"  # 示例文章1：访问150次
    # 在这里添加更多文章，格式："文章链接->访问次数"
]

# 解析URL和访问次数，并初始化访问计数
TARGET_URLS = {}
for url_visit in URL_VISITS:
    url, visits = url_visit.split('->')
    TARGET_URLS[url.strip()] = {
        "url": url.strip(),
        "total_visits": int(visits.strip()),
        "completed_visits": 0
    }

def getHeaders():
    user_agent_list = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.3",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Safari/605.1.1",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604."
    ]
    return {'User-Agent': random.choice(user_agent_list)}

def access_article(url):
    '''访问指定文章'''
    try:
        response = requests.get(
            url=url,
            headers=getHeaders(),
            timeout=10
        )
        print(f"访问成功 | 状态码: {response.status_code} | URL: {url}")
        return True
    except Exception as e:
        print(f"访问失败 | URL: {url} | 错误: {str(e)}")
        return False

if __name__ == '__main__':
    print("开始批量访问文章...")
    last_visit_time = time.time()

    while True:
        current_time = time.time()
        # 检查是否所有文章都已达到总访问次数
        all_articles_completed = all(
            article_info['completed_visits'] >= article_info['total_visits']
            for article_info in TARGET_URLS.values()
        )
        
        if all_articles_completed:
            print("\n所有文章已达到设定的总访问次数，程序结束...")
            break

        # 每60秒访问一次所有未完成的文章
        if current_time - last_visit_time >= 60:
            print("\n=== 开始新一轮访问 ===")
            
            # 遍历所有文章
            for url, article_info in TARGET_URLS.items():
                # 检查是否达到了总访问次数
                if article_info['completed_visits'] < article_info['total_visits']:
                    print(f"\n正在访问文章: {url}")
                    print(f"当前访问次数: {article_info['completed_visits'] + 1}/{article_info['total_visits']}")
                    
                    if access_article(url):
                        article_info['completed_visits'] += 1
                    
                    # 每次访问后短暂休息，避免请求过于频繁
                    time.sleep(random.randint(3, 7))
            
            last_visit_time = current_time
        else:
            # 等待到下一个60秒周期
            remaining_time = 60 - (current_time - last_visit_time)
            print(f"\n等待 {int(remaining_time)} 秒后进行下一轮访问...")
            time.sleep(min(remaining_time, 10))  # 最多等待10秒，然后重新检查
